package com.example.demowithdb.controller;

import com.example.demowithdb.entity.book;
import com.example.demowithdb.mapper.bookMapper;
import com.example.demowithdb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/book")
public class bookController {
    @Resource
    bookMapper BookMap;

    @Autowired
    private UserService userService; // Spring 注入 UserService

    @GetMapping("/list")
    String list(Model model) {
        List<book> books = BookMap.selectList(null);
        model.addAttribute("books", books);
        return "list";  //返回名为"list"的视图，即templates中的list.html
    }

    @GetMapping("/add")
    String addForm() {
        return "add"; //返回名为"add"的视图，即templates中的add.html
    }

    @PostMapping("/add")
    String add(Model model, @ModelAttribute book b, @RequestParam("img") MultipartFile file) {
        if (userService.savePic(b, file)){
            BookMap.insert(b);
            return "success"; //返回名为"success"的视图，即templates中的success.html
        }
        return "failure"; //返回名为"success"的视图，即templates中的success.html
    }

    @GetMapping("/delete")
    String delete(Model model, @RequestParam int id) {
        BookMap.deleteById(id);
        return "success";
    }

    @GetMapping("/edit")
    String editForm(Model model, @RequestParam int id) {
        book b = BookMap.selectById(id);
        model.addAttribute("book", b);
//        model.addAttribute("bookId", bookId);
        return "edit";//返回名为"edit"的视图，即templates中的edit.html
    }

    @PostMapping("/edit")
    String edit(Model model,  @ModelAttribute book b, @RequestParam("img") MultipartFile file) {
        if (userService.savePic(b, file)){
            BookMap.update(b, null);
            return "success"; //返回名为"success"的视图，即templates中的success.html
        }
        return "failure";
    }
}
